<?php

namespace Drinkiit\BlogBundle\Handler;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityManager;
use Drinkiit\UtilisateurBundle\Entity\UtilisateurApp;
use FOS\UserBundle\Entity\UserManger ;

class AdminUtilisateurHandler
{
    protected $form;
    protected $request;
    protected $em;
    protected $controller;

    public function __construct(Form $form, Request $request, Controller $controller, EntityManager $em)
    {
        $this->form    = $form;
        $this->request = $request;
        $this->em      = $em;
        $this->controller = $controller ;
    }

    public function process()
    {
        if( $this->request->getMethod() == 'POST' )
        {
            $this->form->bindRequest($this->request);

            if( $this->form->isValid() )
            {
				$userid = $this->form->get('userid')->getData() ;
				$user = $this->em->getRepository('Drinkiit\UtilisateurBundle\Entity\UtilisateurApp')->find($userid) ;
				/*
				foreach ($this->form as $key => $value) {
					echo "$key : ".$value->getData()."<br>" ;
				}
				exit() ;
				//*/
				
				
				$user->setUsername( $this->form->get('username')->getData() ) ;
				$user->setNom( $this->form->get('nom')->getData() ) ;
				$user->setPrenom( $this->form->get('prenom')->getData() ) ;
				$user->setEmail( $this->form->get('email')->getData() ) ;
				$password = $this->form->get('password')->getData() ;
				if ( !empty($password) )
				{
					$this->controller->get('logger')->info("[INFO] On a bien modifié le mot de passe de l'utilisateur");
					$factory = $this->controller->get('security.encoder_factory');
					$encoder = $factory->getEncoder($user);
					$user->setPassword($encoder->encodePassword($password, $user->getSalt()));
				}
				
				$this->controller->get('logger')->info("[INFO] On a bien modifié les informations de l'utilisateur n°".$user->getId());
				$this->em->flush(); // obligé pour maintenir les modifications
                return true;
            }
            $this->controller->get('logger')->info("[INFO] Le formulaire de modification des informations utilisateur n'est pas valide.") ;
        }

        return false;
    }
}
